package com.haoxuer.discover.area.freemarker;

import com.google.gson.Gson;
import com.haoxuer.discover.area.data.entity.Area;
import com.haoxuer.discover.area.data.service.AreaService;
import com.haoxuer.discover.area.rest.conver.AreaTreeSimpleConver;
import com.haoxuer.discover.area.rest.conver.TreeSimpleConver;
import com.haoxuer.discover.common.freemarker.TextDirective;
import com.haoxuer.discover.config.api.domain.simple.TreeSimple;
import com.haoxuer.discover.config.freemarker.CatalogJsonDirective;
import com.haoxuer.discover.config.freemarker.TextJsonDirective;
import com.haoxuer.discover.config.rest.conver.TreeValueConver;
import com.haoxuer.discover.config.utils.ConverResourceUtils;
import com.haoxuer.discover.data.page.Filter;
import com.haoxuer.discover.data.page.Order;
import com.haoxuer.discover.rest.base.ResponseList;
import com.haoxuer.discover.rest.simple.TreeValue;
import freemarker.core.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by cng19 on 2017/9/3.
 */
@Component("areaTreeJsonDirective")
public class AreaTreeJsonDirective extends TextDirective {

    public List<Order> orders() {
        List<Order> orders = new ArrayList<Order>();
        orders.add(Order.asc("code"));
        return orders;
    }

    @Autowired
    AreaService areaService;

    @Override
    public void handle(Environment env) throws IOException {
        Integer size = getInt("size", 200);
        Integer level = getInt("level", 2);
        List<Filter> filters = new ArrayList<>();
        filters.add(Filter.eq("levelInfo", level));

        List<Area> areas = areaService.list(0, size, filters, orders());
        if (areas != null && areas.size() > 0) {
           List<TreeValue> values=  ConverResourceUtils.converList(areas, new AreaTreeSimpleConver());
            env.getOut().append(new Gson().toJson(values));
        }else{
            env.getOut().append("[]");
        }
    }
}